import ApiService from './api';
import { SalesStats } from '../types';

// 销售查询参数
export interface SalesQueryParams {
  period: 'day' | 'week' | 'month' | 'quarter' | 'year';
  startDate?: string;
  endDate?: string;
  shopId?: string;
  category?: string;
  productId?: string;
}

// 销售对比参数
export interface SalesCompareParams {
  currentPeriod: {
    startDate: string;
    endDate: string;
  };
  previousPeriod: {
    startDate: string;
    endDate: string;
  };
  shopId?: string;
}

// 销售服务
export class SalesService {
  // 获取销售概览
  static async getSalesOverview(params: SalesQueryParams): Promise<{
    totalRevenue: number;
    totalOrders: number;
    totalProducts: number;
    totalCustomers: number;
    averageOrderValue: number;
    conversionRate: number;
    trends: {
      revenueTrend: number;
      ordersTrend: number;
      customersTrend: number;
    };
  }> {
    return await ApiService.get('/admin/sales/overview', params);
  }
  
  // 获取销售趋势数据
  static async getSalesTrends(params: SalesQueryParams): Promise<{
    revenueData: Array<{
      date: string;
      revenue: number;
      orders: number;
      customers: number;
    }>;
    categoryData: Array<{
      category: string;
      revenue: number;
      percentage: number;
    }>;
    regionData: Array<{
      region: string;
      revenue: number;
      orders: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/trends', params);
  }
  
  // 获取实时销售数据
  static async getRealTimeSales(): Promise<{
    todayRevenue: number;
    todayOrders: number;
    onlineUsers: number;
    conversionRate: number;
    recentOrders: Array<{
      orderId: string;
      customerName: string;
      amount: number;
      time: string;
    }>;
    hourlyData: Array<{
      hour: number;
      revenue: number;
      orders: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/realtime');
  }
  
  // 获取商品销售排行
  static async getProductRanking(params: SalesQueryParams & {
    limit?: number;
    sortBy?: 'revenue' | 'quantity' | 'profit';
  }): Promise<Array<{
    productId: string;
    productName: string;
    productImage: string;
    category: string;
    shopName: string;
    revenue: number;
    quantity: number;
    profit: number;
    profitMargin: number;
    trend: number;
  }>> {
    return await ApiService.get('/admin/sales/product-ranking', params);
  }
  
  // 获取店铺销售排行
  static async getShopRanking(params: SalesQueryParams & {
    limit?: number;
    sortBy?: 'revenue' | 'orders' | 'customers';
  }): Promise<Array<{
    shopId: string;
    shopName: string;
    shopLogo: string;
    revenue: number;
    orders: number;
    customers: number;
    averageOrderValue: number;
    trend: number;
  }>> {
    return await ApiService.get('/admin/sales/shop-ranking', params);
  }
  
  // 获取客户分析数据
  static async getCustomerAnalysis(params: SalesQueryParams): Promise<{
    totalCustomers: number;
    newCustomers: number;
    returningCustomers: number;
    customerRetentionRate: number;
    averageLifetimeValue: number;
    customerSegments: Array<{
      segment: string;
      count: number;
      revenue: number;
      percentage: number;
    }>;
    ageDistribution: Array<{
      ageGroup: string;
      count: number;
      percentage: number;
    }>;
    genderDistribution: Array<{
      gender: string;
      count: number;
      percentage: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/customer-analysis', params);
  }
  
  // 获取地域销售分析
  static async getRegionalAnalysis(params: SalesQueryParams): Promise<{
    totalRegions: number;
    topRegions: Array<{
      province: string;
      city: string;
      revenue: number;
      orders: number;
      customers: number;
      percentage: number;
    }>;
    mapData: Array<{
      name: string;
      value: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/regional-analysis', params);
  }
  
  // 获取销售预测
  static async getSalesForecast(params: {
    period: 'week' | 'month' | 'quarter';
    shopId?: string;
  }): Promise<{
    forecastData: Array<{
      date: string;
      predictedRevenue: number;
      confidence: number;
    }>;
    insights: Array<{
      type: 'trend' | 'seasonal' | 'anomaly';
      description: string;
      impact: 'positive' | 'negative' | 'neutral';
    }>;
  }> {
    return await ApiService.get('/admin/sales/forecast', params);
  }
  
  // 获取销售对比分析
  static async getSalesComparison(params: SalesCompareParams): Promise<{
    current: {
      revenue: number;
      orders: number;
      customers: number;
      averageOrderValue: number;
    };
    previous: {
      revenue: number;
      orders: number;
      customers: number;
      averageOrderValue: number;
    };
    changes: {
      revenueChange: number;
      ordersChange: number;
      customersChange: number;
      aovChange: number;
    };
    dailyComparison: Array<{
      date: string;
      currentRevenue: number;
      previousRevenue: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/comparison', params);
  }
  
  // 获取利润分析
  static async getProfitAnalysis(params: SalesQueryParams): Promise<{
    totalProfit: number;
    profitMargin: number;
    grossProfit: number;
    netProfit: number;
    profitByCategory: Array<{
      category: string;
      profit: number;
      margin: number;
    }>;
    profitByShop: Array<{
      shopId: string;
      shopName: string;
      profit: number;
      margin: number;
    }>;
    profitTrends: Array<{
      date: string;
      profit: number;
      margin: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/profit-analysis', params);
  }
  
  // 获取库存分析
  static async getInventoryAnalysis(params: { shopId?: string }): Promise<{
    totalProducts: number;
    lowStockProducts: number;
    outOfStockProducts: number;
    overstockProducts: number;
    inventoryValue: number;
    turnoverRate: number;
    stockAlerts: Array<{
      productId: string;
      productName: string;
      currentStock: number;
      minStock: number;
      status: 'low' | 'out' | 'overstock';
    }>;
    categoryAnalysis: Array<{
      category: string;
      totalProducts: number;
      totalValue: number;
      turnoverRate: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/inventory-analysis', params);
  }
  
  // 获取营销效果分析
  static async getMarketingAnalysis(params: SalesQueryParams): Promise<{
    totalCampaigns: number;
    activeCampaigns: number;
    totalSpent: number;
    totalRevenue: number;
    roi: number;
    campaignPerformance: Array<{
      campaignId: string;
      campaignName: string;
      type: string;
      spent: number;
      revenue: number;
      roi: number;
      conversions: number;
    }>;
    channelPerformance: Array<{
      channel: string;
      spent: number;
      revenue: number;
      roi: number;
      conversions: number;
    }>;
  }> {
    return await ApiService.get('/admin/sales/marketing-analysis', params);
  }
  
  // 导出销售报告
  static async exportSalesReport(params: SalesQueryParams & {
    reportType: 'overview' | 'detailed' | 'products' | 'shops' | 'customers';
    format: 'excel' | 'pdf';
  }): Promise<void> {
    const filename = `sales-report-${params.reportType}-${Date.now()}.${params.format === 'excel' ? 'xlsx' : 'pdf'}`;
    await ApiService.download('/admin/sales/export', filename);
  }
  
  // 获取销售目标完成情况
  static async getSalesTargets(params: { shopId?: string; period: 'month' | 'quarter' | 'year' }): Promise<{
    targets: Array<{
      type: 'revenue' | 'orders' | 'customers';
      target: number;
      actual: number;
      completion: number;
      trend: number;
    }>;
    milestones: Array<{
      date: string;
      description: string;
      achieved: boolean;
    }>;
  }> {
    return await ApiService.get('/admin/sales/targets', params);
  }
  
  // 设置销售目标
  static async setSalesTarget(data: {
    shopId?: string;
    period: 'month' | 'quarter' | 'year';
    type: 'revenue' | 'orders' | 'customers';
    target: number;
    startDate: string;
    endDate: string;
  }): Promise<any> {
    return await ApiService.post('/admin/sales/targets', data);
  }
  
  // 获取销售异常检测
  static async getSalesAnomalies(params: { shopId?: string; days?: number }): Promise<Array<{
    date: string;
    metric: 'revenue' | 'orders' | 'customers';
    actual: number;
    expected: number;
    deviation: number;
    severity: 'low' | 'medium' | 'high';
    description: string;
  }>> {
    return await ApiService.get('/admin/sales/anomalies', params);
  }
}

export default SalesService;
